// pages/insuranceAppo/insuranceAppo.js
import config from "../../config.js";
import util from "../../utils/util.js";
const openIdUrl = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadImg: "https://app.longchg.com/gudongcar/images/upload.jpg",
    //城市列表
    myCarsList: [],
    carList: [],
    carIndex: 0,
    myCarIndex: 0,
    typeList: [],
    typeIndex: 0,
    backAddress: "",
    getAddress: "",
    backAddressIndex: 0,
    getAddressIndex: 0,
    orderType: 0,
    latitude: 0,
    longitude: 0,
    defaultKeeper: {
      name: '',
      header: '',
      houseKeeperId: null
    },
    mindate: util.getDate(),
    date: util.getDate(),
    time: util.getMinute(),
    mintime: util.getMinute(),
    date2: util.getDate(),
    time2: util.getMinute(),
    stepCarLocList: [],
    stepCarLocPickList: [],
    stepCarLocBackList: [],
    // 是否上牌
    hasNo: true,

    // // 服务方式
    // servType:["服务方式1","服务方式2"],
    // servIndex:0,

    // // 投保公司
    // insurance: ["西安市雁塔区唐延南路逸翠园", "西安市雁塔区唐延南路逸翠园","西安市雁塔区唐延南路逸翠园"],
    // insurIndex:0,
    orderId: -1,
    order: null,
    isShowPickLoaction: true,
    isShowReturnLoaction: true,
    isShowPickTime: true,
    isShowReturnTime: true,
    //行驶证
    licenseFr: "https://app.longchg.com/gudongcar/images/licenseA.png",
    licenseBa: "https://app.longchg.com/gudongcar/images/licenseB.png",
    //驾驶证
    idenCardA: "https://app.longchg.com/gudongcar/images/idenCardA.png",
    idenCardB: "https://app.longchg.com/gudongcar/images/idenCardB.png",
    isUploadFr: false,
    isUploadBa: false,
    isUploadIDFr: false,
    isUploadIDBa: false,
    isUploadFirst: true,
    isUploadBaFirst: true,
    isUploadIDFirst: true,
    isUploadBaIDFirst: true,
    isFirst: true //首次加载

  },
  dateChange: function(e) {
    var time = util.getMinute();
    var date = e.detail.value;
    var currentDate = util.getDate();
    var mintime = this.data.mintime;



    if (date != currentDate) {
      mintime = "";
    } else {
      mintime = util.getMinute();
      this.setData({
        time: time
      })
    }


    this.setData({
      date: e.detail.value,
      mintime: mintime,
    })
  },

  timeChange: function(e) {
    this.setData({
      time: e.detail.value
    })
  },
  date2Change: function(e) {
    var time = util.getMinute();
    var date = e.detail.value;
    var currentDate = util.getDate();
    var mintime = this.data.mintime;



    if (date != currentDate) {
      mintime = "";
    } else {
      mintime = util.getMinute();
      this.setData({
        time2:time
      })
    }

    this.setData({
      date2: e.detail.value,
      mintime2:mintime,
    })
  },

  time2Change: function(e) {
    this.setData({
      time2: e.detail.value,
    })
  },

  getTypeList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepServiceTypeList,
      data: {
        start: 0,
        type: 1
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            typeList: res.data.data
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getStepCarLocList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepCarLocList,
      data: {},
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            stepCarLocList: res.data.data,
            stepCarLocPickList: res.data.data[0].stepcarlocations,
            stepCarLocBackList: res.data.data[1].stepcarlocations,
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  submit: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    var user = wx.getStorageSync("user");
    console.log(user);
    var houseKeeperId = that.data.defaultKeeper.houseKeeperId;
    console.log(houseKeeperId);
    var orderType = 7;
    console.log(orderType);
    var serviceType = that.data.typeList[that.data.typeIndex].typeId;
    console.log("服务类型" + serviceType);
    var carId = that.data.myCarsList[that.data.myCarIndex].cid;
    var stepCarId = that.data.carList[that.data.carIndex].carId;
    console.log(carId);
    var comId = 0;
    console.log(comId);
    var orderFrom = 1;
    console.log(orderFrom);
    var addressReturn = that.data.stepCarLocList[1].stepcarlocations[that.data.backAddressIndex].locId;
    var addressPick = that.data.stepCarLocList[0].stepcarlocations[that.data.getAddressIndex].locId;

    console.log(addressReturn);
    var tel = user.tel;

    console.log(tel);
    var pickTime = that.data.date2 + " " + that.data.time2;
    var returnTime = that.data.date + " " + that.data.time;
    console.log(returnTime);

    var isUploadFr = this.data.isUploadFr,
      isUploadBa = this.data.isUploadBa,
      isUploadIDFr = this.data.isUploadIDFr,
      isUploadIDBa = this.data.isUploadIDBa,
      licenseFr = this.data.licenseFr,
      licenseBa = this.data.licenseBa,
      idenCardA = this.data.idenCardA,
      idenCardB = this.data.idenCardB;

    if (!isUploadFr) {
      wx.showToast({
        title: '请选择驾驶证正面',
        icon: 'none',
      })
      return;
    } else if (!isUploadBa) {
      wx.showToast({
        title: '请选择驾驶证反面',
        icon: 'none',
      })
      return;
    } else if (!isUploadFr) {
      wx.showToast({
        title: '请选择行驶证正面',
        icon: 'none',
      })
      return;
    } else if (!isUploadBa) {
      wx.showToast({
        title: '请选择行驶证反面',
        icon: 'none',
      })
      return;
    }


    wx.request({
      url: openIdUrl.stepSubbmit,
      data: {
        houseKeeperId: houseKeeperId,
        orderType: orderType,
        serviceType: serviceType,
        carId: carId,
        carId: carId,
        stepCarId: stepCarId,
        comId: comId,
        pickTime: pickTime,
        orderFrom: orderFrom,
        pickLocId: addressPick,
        returnLocId: addressReturn,
        orderId: that.data.orderId,
        tel: tel,
        name: that.data.defaultKeeper.name,
        returnTime: returnTime,
        licenseFr: licenseFr,
        licenseBa: licenseBa,
        idenCardA: idenCardA,
        idenCardB: idenCardB
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          wx.setStorageSync("orderId", res.data.data.oid);
          wx.setStorageSync("orderConfirmType", 1);
          var orderId = wx.getStorageSync("orderId");
          wx.navigateTo({
            url: "../orderSuccess/success?id=" + orderId,
            complete: function() {
              wx.setStorageSync("orderConfirmType", null);
              wx.setStorageSync("orderId", null);
            }
          })
          // wx.showModal({
          //   title: "恭喜您",
          //   content: "预约成功，车管家将会在10分钟内通过电话与您沟通详情 ，请保持电话畅通！谢谢！",
          //   showCancel: false,
          //   confirmColor: "#137AF0",
          //   success: function() {
          //     wx.switchTab({
          //       url: "../order/order",
          //     })
          //   }
          // })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }

      },
      error: function() {
        wx.showToast({
          title: "请求失败,请联系管理员",
          icon: 'none',
          mask: true,
          duration: 2000
        })
      }
    })

  },
  getCarList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepCarInfo,
      data: {
        // id: 1,
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data.content);
          that.setData({
            carList: res.data.data,

          })


        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getMyCarsList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.myCarsList,
      data: {
        // id: 1,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          var car = res.data.data[0];
          if (that.data.myCarIndex == 0 && that.data.isUploadIDFirst && that.data.isUploadBaIDFirst) {
            that.setData({
              isUploadIDFirst: false,
              isUploadBaIDFirst: false,
              idenCardA: car.wdxlicensePic,
              idenCardB: car.wdxlicensePicB
            })
          }
          that.setData({
            myCarsList: res.data.data,
          })


          //订单服务
          if (that.data.order != null) {
            for (var i = 0; i < that.data.myCarsList.length; i++) {
              var car = that.data.myCarsList[i];
              if (that.data.order.order.cars.cid == car.cid) {
                that.setData({
                  carIndex: i
                })
              }
            }
          }

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },

  carChange: function(e) {
    this.setData({
      carIndex: e.detail.value,
    })
  },
  myCarChange: function(e) {
    var that = this;
    var car = that.data.myCarsList[e.detail.value];
    console.log(car);
    that.setData({
      isUploadIDFirst: false,
      isUploadBaIDFirst: false,
      idenCardA: car.wdxlicensePic,
      idenCardB: car.wdxlicensePicB,
      myCarIndex: e.detail.value,

    })
  },

  typeChange: function(e) {
    this.setData({
      typeIndex: e.detail.value,
    })

    var item = this.data.typeList[this.data.typeIndex];
    switch (item.typeId) {
      case 1:
        this.setData({
          isShowPickLoaction: true,
          isShowReturnLoaction: false,
          isShowPickTime: true,
          isShowReturnTime: false,
        })
        break;
      case 2:
        this.setData({
          isShowPickLoaction: true,
          isShowReturnLoaction: false,
          isShowPickTime: true,
          isShowReturnTime: false,
        })
        break;
      case 3:
        this.setData({
          isShowPickLoaction: false,
          isShowReturnLoaction: true,
          isShowPickTime: false,
          isShowReturnTime: true,
        })
        break;

      default:
        this.setData({
          isShowPickLoaction: true,
          isShowReturnLoaction: true,
          isShowPickTime: true,
          isShowReturnTime: true,
        })
        break;
    }
  },

  servChange: function(e) {
    this.setData({
      servIndex: e.detail.value,
    })
  },

  backChange: function(e) {
    this.setData({
      backAddress: e.detail.value,
    })
  },
  getAddress: function(e) {
    console.log(e);
    this.setData({
      getAddressIndex: e.detail.value,
    })

    console.log(this.data)
  },
  backAddress: function(e) {
    console.log(e);
    this.setData({
      backAddressIndex: e.detail.value,
    })
  },

  selectNo: function() {
    let flag = this.data.hasNo;
    if (flag) {
      this.setData({
        hasNo: false
      })
    } else {
      this.setData({
        hasNo: true
      })
    }
  },

  // 扫描
  scanLicen: function() {
    wx.scanCode({
      scanType: ["barCode", "qrCode", "datamatrix", "pdf417"],
      success: function() {
        //扫描成功
      }
    })
  },

  //上传
  chooseLicenPic: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          uploadImg: tempFilePaths
        })
      },
    })
  },

  toAppoPage: function() {
    wx.navigateTo({
      url: "../insurPlan/insurPlan",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    //获取代步车类型
    this.getTypeList();

    that.getStepCarLocList();
    //判断是否是再次下单或者更改订单类型
    var orderId = options.orderId;
    if (orderId == null) {
      this.setData({
        mindate: util.getDate(),
        mindate2: util.getDate(),
        date: util.getDate(),
        time: util.getMinute(),
        mintime: util.getMinute(),
        mintime2: util.getMinute(),
        date2: util.getDate(),
        time2: util.getMinute(),
      })

      if (wx.getStorageSync('user') != null) {
        that.setData({
          'defaultKeeper.name': wx.getStorageSync("user").housekeeper.name,
          'defaultKeeper.header': wx.getStorageSync("user").housekeeper.image,
          'defaultKeeper.houseKeeperId': wx.getStorageSync("user").housekeeper.keeperId
        })
      }
    } else {
      that.setData({
        orderId: orderId
      })

      //获取订单详情
      that.orderDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //
    var that = this;
    setTimeout(function() {
      that.getMyCarsList();
      that.getCarList();
    }, 300);


    var that = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })
    if (!that.data.isFirst) {
      var houseKeeper = wx.getStorageSync("houseKeeper");
      if (houseKeeper) {
        this.setData({
          "defaultKeeper.name": houseKeeper.name,
          "defaultKeeper.houseKeeperId": houseKeeper.keeperId,
          "defaultKeeper.header": houseKeeper.image,
        })

        console.log(this.data.mainInfo);
      }
    }
    var user = wx.getStorageSync('user');
    console.log(user);
    if (user.licenseA != null && user.licenseB != null && !that.data.isUploadFr && !that.data.isUploadBa) {
      //设置默认车辆图片信息
      console.log(user);
      that.setData({
        licenseFr: user.licenseA,
        licenseBa: user.licenseB,
        isUploadFr: true,
        isUploadBa: true,
        isUploadFirst: false,
        isUploadBaFirst: false
      })
    }

    that.setData({
      isFirst: false
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  orderAction() {
    wx.showModal({
      title: "恭喜您",
      content: "预约成功，车管家将会在10分钟内通过电话与您沟通详情 ，请保持电话畅通！谢谢！",
      showCancel: false,
      confirmColor: "#137AF0",
      success: function() {
        wx.switchTab({
          url: "../order/order",
        })
      }
    })
  },
  chooseMap: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          getAddress: res.address
        })
      },
    })
  },
  chooseMap2: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          backAddress: res.address
        })
      }
    })
  },
  loadMap() {
    wx.navigateTo({
      url: '../map/map',
    })
  },
  orderDetail() {
    var that = this;
    //获取订单详情
    wx.request({
      url: openIdUrl.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: this.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          that.setData({
            order: res.data.data
          })
          that.setOrderData();
        } else {
          wx.showToast({
            title: '订单获取失败！',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  setOrderData() {
    var that = this;
    //订单信息
    var order = that.data.order.order;
    var service = that.data.order.service;

    var houseKeeper = order.housekeeper;
    if (houseKeeper) {
      this.setData({
        "defaultKeeper.name": houseKeeper.name,
        "defaultKeeper.houseKeeperId": houseKeeper.keeperId,
        "defaultKeeper.header": houseKeeper.image,
      })
    }
  },
  changeKeeper: function() {
    var instance = this;
    wx.navigateTo({
      url: '../managerList/managerList',
    })
  },
  //行驶证
  uploadFr: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseFr: tempFilePaths,
          isUploadFr: true,
          isUploadFirst: false
        })

        console.log(that.data.licenseFr);


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseFr[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadFr: true,
              })
              that.data.licenseFr = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBa: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseBa: tempFilePaths,
          isUploadBa: true,
          isUploadBaFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseBa[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadBa: true,
              })
              that.data.licenseBa = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
  //驾驶证正面
  uploadFrID: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardA: tempFilePaths,
          isUploadIDFr: true,
          isUploadIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardA[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadIDFr: true,
              })
              that.data.idenCardA = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBaID: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardB: tempFilePaths,
          isUploadIDBa: true,
          isUploadBaIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardB[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadIDBa: true,
              })
              that.data.idenCardB = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
})